package com.dreamthen.controller;

import com.dreamthen.entity.Person;
import com.dreamthen.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author zengms
 * @Date 2023-11-09 19:09:18
 * 1、加入hibernate-validator依赖
 * 2、把新增的依赖jar包，添加到WEB-INF/lib目录
 * 3、在对应的bean加上相应的注解，并设置message属性（错误提示用）
 * 4、在controller方法中，需要在bean参数前面加上@Valid注解
 * 5、通过BindingResult bindingResult来接收错误提示信息
 **/
@Controller
@RequestMapping("/person")
public class PersonController {

    @PostMapping("/getPerson")
    @ResponseBody
    public Object getPerson(@Valid Person person, BindingResult bindingResult) {
        person.setBirthday(new Date());
        System.out.println(person);
        List<String> errorList = new ArrayList<>();
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorList.add(fieldError.getDefaultMessage());
            }
            return errorList;
        }
        return person;
    }

    @PostMapping("/addPerson")
    @ResponseBody
    public Object addPerson(@RequestBody @Valid Person person, BindingResult bindingResult) {

        person.setBirthday(new Date());
        System.out.println(person);
        List<String> errorList = new ArrayList<>();
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                errorList.add(fieldError.getDefaultMessage());
            }
            return errorList;
        }
        return person;
    }
}
